var $contactTableList = $('#contactList');
var tabsType = $('#contentType').val();

$(function () {
    // select初始化
    $('select').selectpicker();

    // 修改联系人信息弹窗职务交互逻辑
    $('#contactPositionLxr').on('keyup', function (e) {
        var value = $(this).val();
        if (value != '') {
            $(this).parent().removeClass('open');
        }
    });
    $('#contactPositionLxr').next('.dropdown-menu').find('a').on('click', function () {
        $('#contactPositionLxr').val($(this).html());
    })


    // 联系人列表初始化
    contactTable();

    // tabs标签页
    $('#tabsBar').on('click', 'a', function () {
        // tabs标签页切换操作
        var $liActive = $(this).parent('li');
        var contentType = $(this).data('value');
        $liActive.addClass('active').siblings().removeClass('active');
        $('#contentType').val(contentType);

        tabsType = contentType;

        // 重置筛选
        $('#screenWell').find('select').val('').selectpicker('refresh');
        $('#screenWell').find('input').val('');
        $('#dateType label:first-child input').prop('checked', true);
        $('#contactCategory').val('全部联系人').selectpicker('refresh');
        $('#filterContent').collapse('hide');
        $('#contactName').val('');

        // 加载数据
        contactTable();
    })

    // 批处理相关功能
    var $batchBtn = $('#batchBtn');
    $contactTableList.on('check.bs.table', function (e, row, $element) {
        $batchBtn.prop('disabled', false);
    }).on('uncheck.bs.table', function (e,row, $element) {
        var selectRows = $contactTableList.bootstrapTable('getSelections');
        if (selectRows.length == '0') {
            $batchBtn.prop('disabled', true);
        }
    }).on('check-all.bs.table', function (e, row, $element) {
        $batchBtn.prop('disabled', false);
    }).on('uncheck-all.bs.table', function (e, row, $element) {
        $batchBtn.prop('disabled', true);
    });
    // 批处理交互效果
    $('#batchCollapse').on('shown.bs.collapse', function () {
        $(document).on('click', function (e) {
            var target = $(e.target);
            if(!target.is('#batchCollapse') && !target.is('#batchCollapse *') && !target.is('.jconfirm-box-container') && !target.is('.jconfirm-box-container *')) {
                $('#batchCollapse').collapse('hide');
            }
        });
    });
    $('#batchDate').datepicker({
        language: "zh-CN",
        autoclose: true,
        clearBtn: true,
        todayHighlight: true,
        format: "yyyy-mm-dd",
        startDate: new Date()
    });

    // 筛选展开关闭
    $('.filter-well > a').on('click', function () {
        $(this).prev('.row').slideToggle();
        if ($(this).hasClass('active')) {
            $(this).html('收起<i class="mdi mdi-chevron-up"></i>');
        } else {
            $(this).html('展开<i class="mdi mdi-chevron-down"></i>');
        }
        $(this).toggleClass('active');
    })

    $('#screenWell').find('select, input').on('change', function () {
        contactTable();
    });
    $('#dateType input').on('click', function () {
        contactTable();
    });
    $('#contactCategory').on('change', function () {
        contactTable();
    })

    // 标签
    tagsList();
    // 行业
    industryList();
    // 地区
    provinceList();
    // 录入时间
    $('#screenTime').datepicker({
        language: "zh-CN",
        autoclose: true,
        clearBtn: true,
        todayHighlight: true,
        format: "yyyy-mm-dd"
    });

    // 标签弹窗
    $('#editTags').on('show.bs.modal', function () {
        tagsModal();
    });
});

/**
 * 功能：列表初始化
 * */
function contactTable() {
    $contactTableList.bootstrapTable('destroy');
    $contactTableList.bootstrapTable({
        classes: 'table contact-table',
        url: '/contact/contactList',                            // 请求地址
        method: 'post',                                         // 请求方式
        contentType: "application/x-www-form-urlencoded",       // 请求内容类型
        dataType: "json",                                       // 数据类型
        striped: true,                                          // 是否显示行间隔色
        sortable: true,                                         // 是否启用排序
        sortOrder: "desc",                                      // 排序方式
        sortName: 'followTm',                                   // 排序字段
        cache: false,                                           // 是否使用缓存
        showColumns: false,                                     // 显示隐藏列
        showRefresh: false,                                     // 显示刷新按钮
        showToggle: false,                                      // 切换显示样式
        showFooter: false,                                      // 显示Table脚部
        pagination: true,                                       // 是否显示分页
        showPaginationSwitch: false,                            // 是否显示分页按钮
        clickToSelect: false,                                    // 是否启用点击选中行
        singleSelect: false,
        minimumCountColumns: 2,                                 // 最少要显示的列数
        undefinedText: '',                                      // cell没有值时显示
        sidePagination: "server",                               // 分页方式：client客户端分页，server服务端分页
        uniqueId: 'contactId',
        idField: 'contactId',
        pageSize: globalPageSize,                               // 每页的记录行数
        pageNumber: 1,                                          // 初始化加载第1页，默认第1页
        pageList: globalPageList,                               // 可供选择的每页的行数
        queryParams: queryParams,                               // 查询参数
        columns: [
            {title: '联系人ID', field: 'contactId', visible: false},
            {title: '全选', field: 'checked', align: 'center', checkbox: true, valign: 'middle',
                formatter: function (value, row) {
                    if (row.abolishState == 2) {
                        return {
                            disabled: true
                        }
                    } else {
                        return {
                            disabled: false
                        }
                    }
                }
            },
            {title: '', field: 'accessUrl', align: 'left', valign: 'middle', width: '100', formatter: contactTableList.head},
            {title: '联系人姓名', field: 'contactName', align: 'left', valign: 'middle', width: '30%', formatter: contactTableList.info},
            {title: '最近跟进时间', field: 'followTm', sortable: true, align: 'left', valign: 'middle', formatter: contactTableList.lastTime},
            {title: '计划跟进时间', field: 'followPlanTime', sortable: true, align: 'left', valign: 'middle', formatter: contactTableList.planTime},
            {title: '标签', field: 'tag', align: 'left', valign: 'middle', width: '', formatter: contactTableList.tag},
            {title: '操作', field: 'operate', align: 'right', valign: 'middle', width: '', events: contactTableList, formatter: contactTableList.operation},
        ],
        responseHandler: function (result) {
            if (result.code == "000000") {
                var obj = {
                    "rows": result.data,
                    "total": result.totalRecords//总条数
                };
            } else {
                var obj = {
                    "total": 0,
                    "rows": [],
                }
            }
            return obj;
        },
        onLoadSuccess: function (data) {
            // $("[data-toggle='tooltip']").tooltip();
            // console.log($('.contact-header'));
            $(document).on('mouseenter', '.contact-header', function () {
                var $this = $(this);
                var scrollTop = $(document).scrollTop();
                var tLeft = $(this).offset().left;
                var tTop = $(this).offset().top;

                $this.removeClass('hide-action');
                $this.css('z-index', '10').find('.action').css({
                    position: 'fixed',
                    left: tLeft + 38,
                    top: tTop - scrollTop - 29,
                });
                $(document).scroll(debounce(function () {
                    $this.addClass('hide-action');
                }, 200, true));
            }).on('mouseleave', '.contact-header', function () {
                $(this).css('z-index', '1')
            });

            $('#batchBtn').removeClass('hidden');
        },
        onLoadError: function (status) {
            if (status == 403) {
                alert("权限不足！禁止访问！");
            } else {
                //加载失败时执行
                alert("加载失败！");
            }
        },
        formatLoadingMessage: function () {
            return "请稍等，加载中...";
        },
        formatNoMatches: function () {
            return '无符合条件的记录';
        },
    });
}

/**
 * 功能：筛选条件
 * */
function queryParams(params) {
    params.pageSize = params.limit;
    params.pageIndex = (params.offset / params.limit) + 1;
    params.sortName = params.sort;
    params.sortOrder = params.order;

    // tab标签类别
    params.tabType = $('#contentType').val();               // 全部联系人 传空  1最近7天跟进  2未跟进30天 3计划跟进 4意向联系人   3 4先不做
    // 筛选分类
    params.industry = $('#screenIndustry').val();           // 行业
    params.provinceId = $('#screenProvince').val();         // 地区id
    params.contactPosition = $('#screenPost').val();        // 职务
    params.onTheJobSituation = $('#screenJob').val();       // 在职情况 0: 在职; 1: 离职
    params.companyType = $('#screenCompanyType').val();     // 企业性质
    params.membershipLevel = $('#screenNature').val();      // 客户性质  0非会员 1会员
    params.createTm = $('#screenTime').val();               // 创建时间
    params.tag = $('#screenTags').val();                    // 标签
    /*if (screenType) {
        params.abolishState = $('#screenAbolish').val();        // 废止状态
    }*/
    // 全部、本周、本月
    params.dateType = $("#dateType input:checked").val();
    // 联系人类别
    params.abolishState = $("#contactCategory").val() == '全部联系人' ? '' : $("#contactCategory").val();

    return params;
}

/**
 * 功能：标签
 * */
function tagsList() {
    $.ajax({
        url: '/contact/selectTag',
        type: 'post',
        dataType: 'json',
        data: {
            bs: '1'     // 标识  0-管理端 1-用户端
        },
        success: function (data) {
            if (data.code == '000000') {
                var tagsList = data.data;
                var optionList = '<option value="">不限</option>';
                for (var i = 0; i < tagsList.length; i++) {
                    optionList += '<option value="' + tagsList[i] + '">' + tagsList[i] + '</option>';
                }
                $('#screenTags').html(optionList).selectpicker('refresh');
            }
        }
    })
}

/**
 * 功能：行业渲染
 * */
function industryList() {
    $.ajax({
        url: '/contact/selectIndustry',
        type: 'post',
        dataType: 'json',
        data: {
            bs: '1'     // 标识  0-管理端 1-用户端
        },
        success: function (data) {
            var industryList = data.data;
            var optionList = '<option value="">不限</option>';
            for(var i = 0; i< industryList.length; i++){
                optionList += '<option value="' + industryList[i].code + '">' + industryList[i].name + '</option>';
            }
            $('#screenIndustry').html(optionList).selectpicker('refresh');
        }
    })
}

/**
 * 功能：地区渲染
 * */
function provinceList() {
    $.ajax({
        url: '/contact/selectProvince',
        type: 'post',
        dataType: 'json',
        data: {
            bs: '1'     // 标识  0-管理端 1-用户端
        },
        success: function (data) {
            var provinceList = data.data;
            var optionList = '<option value="">不限</option>';
            for(var i = 0; i< provinceList.length; i++){
                optionList += '<option value="' + provinceList[i].code + '">' + provinceList[i].name + '</option>';
            }
            $('#screenProvince').html(optionList).selectpicker('refresh');
        },
    })
}

/**
 * 功能：联系人列表自定义内容
 * */
var contactTableList = {
    'click .sendCodeBtn': function (e, value, row, index) {
        $.ajax({
            url: '/contact/contactSendCode',
            type: "post",
            dataType: "json",
            data: {
                contactInformation: row.contactInformation,     // 手机号
                contactId: row.contactId,                       // 联系人id
            },
            success: function (data) {
                if (data.code = '000000') {
                    $.alert({
                        title: '提醒',
                        content: data.data,
                        buttons: {
                            confirm: {
                                text: '确定',
                                btnClass: 'btn-primary',
                                action: function () {
                                    // 发码成功，更新行数据
                                    var flag = 0;
                                    if (data.data == '兑换码发放成功') {
                                        flag = 1;
                                    }
                                    $('#contactList').bootstrapTable('updateByUniqueId', {
                                        id: row.contactId,
                                        row: {
                                            isSendCode: flag,
                                        }
                                    });
                                }
                            },
                        }
                    })
                } else {
                    $.alert({
                        title: '提示',
                        content: '发码操作失败，错误代码：' + data.data.code
                    });
                }
            },
            error: function () {
                $.alert({
                    title: '提示',
                    content: '发码操作失败，请刷新页面重试!'
                });
            }
        })
    },
    head: function (value, row, index, field) {
        // console.log(value, row, index, field);
        // var imgNode = value ? ('<img src="' + row.accessUrl + '" alt="">') : row.contactName.split('')[0];
        var imgNode;
        // 解决联系人姓名为null报错的问题
        if (value) {
            imgNode = '<img src="' + row.accessUrl + '" alt="">';
        } else {
            row.contactName ? imgNode = row.contactName.split('')[0] : imgNode = '';
        }

        var headNode;
        if (row.abolishState == 1) {
            // 启用联系人
            headNode = '<div id="head-' + index +'" class="contact-header">' +
                '<a href="javaScript:void(0);">' + imgNode + '</a>' +
                '<div class="action">' +
                '<ul><li><a href="javaScript:void(0);" onclick="callCenter(\'' + row.contactId + '\', \'' + row.customerId + '\', \'' + row.contactNature + '\')" title="线上电话"><i class="mdi mdi-headphones"></i></a></li>' +
                '<li><a href="javaScript:void(0);" onclick="goOnline(\'' + row.customerId + '\', \'' + row.contactId + '\', \'' + row.contactName + '\', \'' + row.contactInformation + '\', \'拜访\', );" title="拜访"><i class="mdi mdi-glassdoor"></i></a></li>' +
                '<li><a href="javaScript:void(0);" onclick="goOnline(\'' + row.customerId + '\', \'' + row.contactId + '\', \'' + row.contactName + '\', \'' + row.contactInformation + '\', \'微信交流\', );" title="微信交流"><i class="mdi mdi-wechat"></i></a></li>' +
                '<li><a href="javaScript:void(0);" onclick="goOnline(\'' + row.customerId + '\', \'' + row.contactId + '\', \'' + row.contactName + '\', \'' + row.contactInformation + '\', \'线下电话\', );" title="线下电话"><i class="mdi mdi-phone"></i></a></li>' +
                '<li><a href="javaScript:void(0);" onclick="goOnline(\'' + row.customerId + '\', \'' + row.contactId + '\', \'' + row.contactName + '\', \'' + row.contactInformation + '\', \'电子邮件\', );" title="电子邮件"><i class="mdi mdi-email-variant"></i></a></li>' +
                '<li><a href="javaScript:void(0);" onclick="goOnline(\'' + row.customerId + '\', \'' + row.contactId + '\', \'' + row.contactName + '\', \'' + row.contactInformation + '\', \'陪访\', );" title="陪访"><i class="mdi mdi-account-multiple"></i></a></li></ul></div></div>';
        } else if (row.abolishState == 2) {
            // 废止联系人
            headNode = '<div id="head-' + index +'" class="contact-header"><a href="javaScript:void(0);" class="abolish">' + imgNode + '</a><i class="mdi mdi-do-not-disturb"></i></div>';
        }
        return headNode;
    },
    info: function (value, row, index, field) {
        // 联系人职务: 0 公司管理 1 财务 2 人力 3 其他
        // console.log(row.contactPosition)
        var contactPosition;
        switch (row.contactPosition) {
            case '0':
                contactPosition = '公司管理';
                break;
            case '1':
                contactPosition = '财务';
                break;
            case '2':
                contactPosition = '人力';
                break;
            default:
                contactPosition = '其他';
                break;
        }

        var name = value;                                                     // 联系人姓名
        var companyName = row.customerName || '-';                            // 客户名称
        var contactNature = row.contactNature ? '个人联系人' : '企业联系人';      // 联系人性质

        var html = '<div class="info"><h5><a href="JavaScript:void(0);" onclick="contactDetail(\'' + row.contactId + '\')">' + name + '</a><span>' + contactPosition + '</span><span>' + contactNature + '</span>';
        if (row.membershipLevel) {
            html += '<span class="vip">VIP' + row.membershipLevel + '</span>';
        }
        if(row.contactNature == 0) {
            html += '</h5><p><a href="JavaScript:void(0);" onclick="customerDetail(\'' + row.customerId + '\')">' + companyName + '</a></p></div>';
        }else{
            if(row.companyName == null) {
                html += '</h5><p><a href="JavaScript:void(0);">-</a></p></div>';
            }else {
                html += '</h5><p><a href="JavaScript:void(0);">' + row.companyName + '</a></p></div>';
            }

        }


        return html;
    },
    lastTime: function (value, row, index, field) {
        var html;
        if (value) {
            var followTime = new Date(value).Format("yyyy-MM-dd");
            //var timeArr = followTime.split(' ');
            //html = '<div class="time">' + timeArr[0] + '<span>' + timeArr[1] + '</span></div>';
            html = '<div class="time">' + followTime + '</div>';
        } else {
            html = '暂无跟进记录';
        }
        return html;
    },
    planTime: function (value, row, index, field) {
        var html;
        if (value) {
            var followTime = new Date(value).Format("yyyy-MM-dd");
            html = '<div class="time">' + followTime + '</div>';
        } else {
            html = '暂无跟进计划';
        }
        return html;
    },
    tag: function (value, row, index, field) {
        var html = '';
        if (value) {
            var tagsArr = value.split(',');
            for (var i = 0; i < tagsArr.length; i++) {
                if (i > 4) {
                    break;
                }
                html += '<span class="label label-warning">' + tagsArr[i] + '</span>';
            }
        } else {
            html = '暂无标签';
        }
        return html;
    },
    operation: function (value, row, index, field) {
        var html = '<button type="button" class="btn btn-default" onclick="contactDetail(\'' + row.contactId + '\')"><i class="mdi mdi-eye"></i>查看</button>';
        html += '<button type="button" class="btn btn-default" onclick="editContact(\'' + row.contactId + '\')"><i class="mdi mdi-pencil"></i>修改</button>';
        if (row.abolishState == 1) {    // 1-启用联系人  2-废止联系人
            html += '<button type="button" class="btn btn-default" onclick="updateAbolishState(\'' + row.contactId + '\', \'' + row.customerId + '\', \'' + row.contactName + '\', \'' + row.contactInformation + '\', \'' + row.contactNature + '\', \'' + row.abolishState + '\', \'' + index + '\')"><i class="mdi mdi-close-circle-outline"></i>废止</button>';
        } else {
            html += '<button type="button" class="btn btn-default" onclick="updateAbolishState(\'' + row.contactId + '\', \'' + row.customerId + '\', \'' + row.contactName + '\', \'' + row.contactInformation + '\', \'' + row.contactNature + '\', \'' + row.abolishState + '\', \'' + index + '\')"><i class="mdi mdi-check-circle-outline"></i>启用</button>';
        }

        if (row.abolishState == 2) {
            return html;
        }


        if (row.topContact == '1' || row.topContact == null) {   //常用 0 常用 1 不常用
            html += '<button type="button" data-stata="0" class="btn btn-default" onclick="searchCustomerPoolLists(this, \'' + row.contactId + '\')"><i class="mdi mdi-approval"></i>设为常用</button>';
        } else {
            html += '<button type="button" data-stata="1" class="btn btn-default btn-success" onclick="searchCustomerPoolLists(this, \'' + row.contactId + '\')"><i class="mdi mdi-check-circle-outline"></i>取消常用</button>';
        }
        if (row.isSendCode == '0') {
            // 可发码
            html += '<button type="button" class="btn btn-default sendCodeBtn">发码</button>';
        } else {
            // 不可发码
            html += '<button type="button" class="btn btn-default sendCodeBtn" disabled>发码</button>';
        }
        //目前意向   0有意向 1无意向
        if (tabsType != '3') {
            if (row.currentIntention == '1' || row.currentIntention == null || row.currentIntention == '') {
                html += '<button type="button" data-currentintention="0" class="btn btn-default" onclick="searchCurrentIntention(this, \'' + row.contactId + '\')"><i class="mdi mdi-approval"></i>设为意向</button>';
            } else {
                html += '<button type="button" data-currentintention="1" class="btn btn-default btn-success" onclick="searchCurrentIntention(this, \'' + row.contactId + '\')"><i class="mdi mdi-check-circle-outline"></i>取消意向</button>';
            }
        }
        //移除计划
        if (row.followPlanTime != null && tabsType != '4') {
            html += '<button type="button" id="followPlanTimes" class="btn btn-default" onclick="updateFollowPlanTime(\'' + row.contactId + '\')"><i class="mdi mdi-approval"></i>移除计划</button>';
        }

        return html;
    },
}

/**
 * 功能：跳转线上线下电话跟进
 * 参数：1-线上电话  2-拜访  3-微信  4-线下电话  5-邮箱  6-陪访
 * */
function goOnline(customerId, contactId, contactName, contactInformation, name) {
    var type = '';
    var title = '跟进';

    // 线上电话
    if (name == '线上电话') {
        type = "1";
        title = '联系人跟进-线上电话';
    }
    // 拜访
    if (name == '拜访') {
        type = "2";
        title = '联系人跟进-拜访';
    }
    // 微信
    if (name == '微信交流') {
        type = "3";
        title = '联系人跟进-微信交流';
    }
    // 线下电话
    if (name == '线下电话') {
        type = "4";
        title = '联系人跟进-线下电话';
    }
    // 电子邮件
    if (name == '电子邮件') {
        type = "5";
        title = '联系人跟进-电子邮件';
    }
    // 陪访
    if (name == '陪访') {
        type = "6";
        title = '联系人跟进-陪访';
    }
    parent.$(parent.document).data('multitabs').create({
        iframe: true,
        title: title,
        url: "/front/contactManager/user/contactFollow?type=" + type + "&bs=0" +
            "&customerId=" + customerId + "&contactId=" + contactId + "&contactName=" + contactName + "&contactInformation=" + contactInformation
    }, true);
}

function callCenter (contactId, customerId, customerType) {
    /*parent.$(parent.document).data('multitabs').create({
        iframe : true,
        title : "线上电话",
        url : "/front/callCenter"
    }, true);*/
    var contactPersonData = [];
    $.ajax({
        // url: "/customerController/selectContacts?customerId=" + customerId,
        url: "/customerController/selectMyContacts?contactId=" + contactId,
        type: 'GET',
        datatype: 'json',
        async: false,
        success: function (data) {
            if (data) {
                if (data.code == '000000') {
                    contactPersonData = data.data;
                }
            }
        }
    });
    window.parent.callModal(customerId, contactPersonData,3, '', customerType);
}

/**
 * --列表序列号
 */
function indexFormat(value, row, index) {
    return index + 1;
}

/**
 * 职务
 * @param value
 * @param row
 * @param index
 * @returns {string}
 */
function contactPositionFormat(value, row, index) {
    if (value == null || value == undefined) {
        return "-";
    } else if (0 == value) {
        return "<span class='label label-success-light'>公司管理</span>";
    } else if (1 == value) {
        return "<span class='label label-yellow-light'>财务</span>";
    } else if (2 == value) {
        return "<span class='label label-yellow-light'>人力</span>";
    } else if (3 == value) {
        return "<span class='label label-yellow-light'>其他</span>";
    }
}

/**
 * 自定义操作列内容
 */
function genderOpt(value, row, index) {
    if (row.abolishState == 1) {
        return '<button type="button" id="followUp" class="btn btn-default" data-index="0">\n' +
            '<i class="mdi mdi-image-filter-tilt-shift"></i>跟进</button>' +
            '<a style="margin: 0 6px;" type="button" id="edit" class="btn btn-xs btn-default edit-btn" title="修改" data-toggle="tooltip" onclick=\'editContact("' + row.contactId + '")\'>' +
            '<i class="mdi mdi-pencil" style="padding-right: 6px;"></i>修改</a>';
    } else {
        return '<span style="color: #ccc;text-decoration: line-through;" >-</span>';
    }
}

/**
 * 联系人废止状态  1启动 2废止
 * @param value
 * @param row
 * @param index
 * @returns {string}
 */
function abolishStateFormat(value, row, index) {
    var is_checked = '';
    if (value == null || value == undefined || value == 0) {
        return "-";
    } else if (value == 2) {
        is_checked = '';
    } else if (value == 1) {
        is_checked = 'checked="checked"';
    }
    var poolStateHtml = '<label class="lyear-switch switch-solid switch-success">' +
        '<input type="checkbox" id="abolishState' + row.contactId + '" ' + is_checked + '>' +
        '<span  onClick="updateAbolishState(\'' + row.contactId + '\', \'' + row.customerId + '\',\'' + row.contactName + '\',\'' + row.contactInformation + '\',\'' + value + '\')"></span>' +
        '</label>';
    return poolStateHtml;
}

/**
 * 开启/废止客户详情下联系人
 * @param contactId 联系人id
 * @param customerId 客户id
 * @param contactName 联系人姓名
 * @param contactInformation 联系方式
 * @param abolishState 废止状态  1启动 2废止
 */
function updateAbolishState(contactId, customerId, contactName, contactInformation, contactNature, abolishState, index) {
    var abolishState = (abolishState == 1) ? 2 : 1; // 发送参数值跟当前参数值相反
    var confirmMessage = '';
    var btnClass;
    if (abolishState == 1) {
        confirmMessage = "确定启用联系人吗？";
        btnClass = 'btn-primary';
    } else {
        confirmMessage = "确定废止联系人吗？";
        btnClass = 'btn-danger';
    }

    $.alert({
        title: '系统提示',
        content: confirmMessage,
        buttons: {
            confirm: {
                text: '确认',
                btnClass: btnClass,
                action: function () {
                    $.ajax({
                        type: "post",
                        url: "/customer/updateAbolishState",
                        data: {
                            contactId,
                            customerId,
                            contactName,
                            contactInformation,
                            abolishState,
                            contactNature
                        },
                        dataType: 'json',
                        success: function (data, status) {
                            if (data.code == '000000') {
                                $('#contactList').bootstrapTable('updateRow', {
                                    index,
                                    row: {
                                        abolishState
                                    }
                                });
                            } else {
                                promptInfo(data.message + '(错误代码：' + data.code + ')');
                            }
                        },
                        error: function () {
                            promptInfo('修改失败，请稍后再试!');
                        }
                    });
                }
            },
            cancel: {
                text: '取消',
            }
        }
    });
}

/**
 * 联系人类型(在职 0  离职 1)
 * @param value
 * @param row
 * @param index
 * @returns {string}
 */
function poolTypeFormat(value, row, index) {
    if (value == null || value == undefined) {
        return "-";
    } else if (0 == value) {
        return "<span class='label label-success-light'>在职</span>";
    } else if (1 == value) {
        return "<span class='label label-info-light'>离职</span>";
    }
}

/**
 * 目前意向(0有意向, 1无意向)
 * @param value
 * @param row
 * @param index
 * @returns {string}
 */
function currentIntentionFormat(value, row, index) {
    if (value == null || value == undefined) {
        return "-";
    } else if (0 == value) {
        return "<span class='label label-success-light'>有意向</span>";
    } else if (1 == value) {
        return "<span class='label label-info-light'>无意向</span>";
    }
}

/**
 * 点击客户姓名跳转客户详情页面
 * @param value
 * @param row
 * @param index
 * @returns {string}
 */
function customerNameFormat(value, row, index) {
    if (value == null) {
        value = '';
    }
    return '<a style="color:red;cursor:pointer;text-decoration:underline;" target="_blank"  onclick=\'customerDetail(\"' + row.customerId + '")\'>' + value + '</a>';
}

function customerDetail(customerId) {
    $.ajax({
        url: '/customerController/selectCustomerSelf',
        type: 'POST',
        dataType: "json",
        data: {
            "customerId" : customerId
        },
        success: (function (data) {
            if (data.code == "000000") {
                if(data.data == true) {
                    parent.$(parent.document).data('multitabs').create({
                        iframe: true,
                        title: '客户详情',
                        url: "/front/user/customerManager/customerDetail?customerId=" + customerId
                    }, true);
                }else{
                    $.alert("暂无权限查看该客户");
                }

            } else {
                $.alert("操作失败");
            }
        }),
        error: (function () {
            $.alert("失败");
        })
    });



}

/**
 * 点击联系人姓名跳转联系人详情页面
 * @param value
 * @param row
 * @param index
 * @returns {string}
 */
function contactNameFormat(value, row, index) {
    if (value == null) {
        value = '';
    }
    return '<a style="color:red;cursor:pointer;text-decoration:underline;" target="_blank"  onclick=\'contactDetail(\"' + row.contactId + '")\'>' + value + '</a>';
}

function contactDetail(contactId) {
    parent.$(parent.document).data('multitabs').create({
        iframe: true,
        title: '联系人详情',
        url: "/front/user/contactManager/contactDetail?contactId=" + contactId
    }, true);
}


// 渲染城市列表
function getProvinceLxr() {
    let provinceNames = [];
    $.each(cityJson[0], function (key, value) {
        provinceNames.push('<option value="' + key + '">' + value + '</option>')
    });
    $('#province').html(provinceNames.join(''));
    getCityLxr('110000')
}

// 根据省获取市
function getCityLxr(provinceId) {
    $('#city').html('');
    let key = '0,' + provinceId;
    let cityNames = [];
    $.each(cityJson[key], function (key, value) {
        cityNames.push('<option value="' + key + '">' + value + '</option>')
    });
    $('#city').html(cityNames.join(''));
}

// '切换城市'
function changeCityLxr() {
    getCityLxr($('#province').val());
}

/**
 * 新增联系人
 */
function addContact() {
    parent.$(parent.document).data('multitabs').create({
        iframe: true,
        title: '新增联系人',
        url: "/front/contactManager/addContact?customerId=" + ""
    }, true);
}

/**
 * 新增联系方式
 */
function addContactInformation() {
    //获取当前行
    var row = $contactTableList.bootstrapTable('getSelections');
    if (row.length == 0 || row.length > 1) {
        $.alert("请选择一行数据后再操作");
    } else {
        //$.alert(row[0].contactId);
        parent.$(parent.document).data('multitabs').create({
            iframe: true,
            title: '新增联系方式',
            url: "/front/contactManager/addContactInformation?contactId=" + row[0].contactId + "&contactInformationBs=1" + "&customerId=" + row[0].customerId
        }, true);

    }
}

/**
 * 批量废止联系人
 */
function batchAbolition() {
    var idLists = [];
    var idList = $contactTableList.bootstrapTable('getAllSelections');

    if (idList.length == 0) {
        $.alert("请选择一行数据后再操作");
    } else {
        // for (var i = 0; i < idList.length; i++) {
        //     console.log(idList[i]);
        //     idLists.push(idList[i]);
        //     alert(idList[i].contactId);
        // }
    }
}

/**
 * 修改联系人
 */
function editContact(contactId) {

    $.ajax({
        url: '/contact/selectContactById',
        type: 'POST',
        dataType: "json",
        data: {
            contactId: contactId,
        },
        success: (function (data) {
            $('#editModel').modal('show');
            if (data.code == "000000") {
                $("#contactIdLxr").val(data.data.contactId);
                $("#customerIdLxr").val(data.data.customerId);
                $("#contactNatureLxr").val(data.data.contactNature);
                $("#contactNameLxr").val(data.data.contactName);                // 姓名
                $("#contactPositionLxr").val(data.data.contactPosition);        // 职务
                $("#onTheJobSituationLxr").val(data.data.onTheJobSituation);  //在职情况
                $("#contactInformationLxr").val(data.data.contactInformation);
                $("#mailBoxLxr").val(data.data.mailBox);  //wx
                $("#wxLxr").val(data.data.wx);  //微信
                $("#homeAddressLxr").val(data.data.homeAddress);  //微信
                $("#companyAddressLxr").val(data.data.companyAddress);  //微信

                $('#editModel select').selectpicker('refresh');
                //$("#contactState").val(data.data.contactState);  //联系人类型    主联系人-1   从联系人-2
            } else {
                alert("请求失败");
            }
        }),
        error: (function (res) {
            alert("请求失败");
        })
    })
}

/**
 * 提交修改联系人
 * */
function updateContact() {
    var contactId = $('#contactIdLxr').val(); //客户下联系人id
    var customerId = $('#customerIdLxr').val(); //客户下联系人id
    var contactNature = $('#contactNatureLxr').val(); //联系人性质  0企业联系人  1个人联系人
    var contactName = $('#contactNameLxr').val(); //联系人姓名
    var contactPosition = $('#contactPositionLxr').val();  //职务
    var contactInformation = $('#contactInformationLxr').val();  //联系方式
    var onTheJobSituation = $('#onTheJobSituationLxr').val();  //在职情况
    var wx = $('#wxLxr').val();  //微信
    var mailBox = $('#mailBoxLxr').val();  //邮箱
    var homeAddress = $('#homeAddressLxr').val();  //家庭住址
    var companyAddress = $('#companyAddressLxr').val();  //公司地址

    var jsonData = {
        contactId: contactId,
        contactName: contactName,  //联系人姓名
        contactPosition: contactPosition,  //职务
        contactInformation: contactInformation,  //联系方式
        onTheJobSituation: parseInt(onTheJobSituation),  //在职情况
        wx: wx,  //微信
        mailBox: mailBox,  //邮箱
        homeAddress : homeAddress, //家庭住址
        companyAddress: companyAddress, //公司地址
        customerId: customerId,
        contactNature : contactNature
    };

    $.ajax({
        url: '/customer/updateCustomerContactPerson',
        type: 'POST',
        dataType: "json",
        contentType: "application/json;charset=utf-8",
        data: JSON.stringify(jsonData),
        success: (function (data) {
            if (data.code == "000000") {
                $('#editModel').modal('hide');
                $contactTableList.bootstrapTable('refresh');
            } else {
                $.alert("操作失败");
            }
        }),
        error: (function () {
            $.alert("失败");
        })
    });


}

function promptInfo(content) {
    $.alert({
        title: '系统提示',
        content: content,
        buttons: {
            confirm: {
                text: '确认',
                btnClass: 'btn-primary'
            }
        }
    });
}

function searchCustomerPoolList(_this, type, value) {
    // 初始化筛选
    $('#contentType').val('');
    $('#tabsBar li').removeClass('active').first().addClass('active');
    $('#screenWell input').val('');
    $('#screenWell select').val('').selectpicker('refresh');
    $('#dateType label:first-child input').prop('checked', true);
    $('#contactCategory').val('全部联系人').selectpicker('refresh');

    var $this = $(_this);
    if (type === 5) {//普通条件查询
        $contactTableList.bootstrapTable('refreshOptions', {
            queryParams: function (params) {
                params.pageSize = params.limit;
                params.pageIndex = (params.offset / params.limit) + 1;
                params.sortName = params.sort;
                params.sortOrder = params.order;

                params.contactName = $('#contactName').val();
                params.bs = '1';

                return params;
            }
        });
    } else if (type == 6) {//高级搜索条件查询
        $contactTableList.bootstrapTable('refreshOptions', {
            queryParams: function (params) {
                params.pageSize = params.limit;
                params.pageIndex = (params.offset / params.limit) + 1;
                params.sortName = params.sort;
                params.sortOrder = params.order;

                params.customerName = $('#custName').val();
                params.contactInformation = $('#contactInformation').val()
                params.abolishState = $('#abolishState').val()
                params.bs = '1';
                return params;
            }
        });

    }
}

// 设置为常用联系人
function searchCustomerPoolLists(_this, contactId) {
    var $this = $(_this);
    var $stata = $this.data('stata');
    // console.log(contactId)
    $.ajax({
        url: "/contact/setUpTopContact",
        async: true,
        data: {
            contactId: contactId,
            topContact: $stata, //常用 0常用 1不常用
        },
        type: "POST",
        dataType: "json",
        success: function (data) {
            if (data.code == "000000") {
                $stata = Number(!$stata);
                $this.data('stata', $stata);
                if ($stata) {
                    $this.addClass('btn-success').html('<i class="mdi mdi-check-circle-outline"></i>取消常用');
                } else {
                    $this.removeClass('btn-success').html('<i class="mdi mdi-approval"></i>设为常用');
                }
            } else {
                $.alert("操作失败");
            }
        }
    })

}

//移除意向联系人
function searchCurrentIntention(_this, contactId) {
    var $this = $(_this);
    var $currentIntention = $this.data('currentintention');
    $.ajax({
        url: "/contact/updateContactCurrentIntention",
        async: true,
        data: {
            contactId: contactId,
            currentIntention: $currentIntention, //目前意向   0有意向 1无意向
        },
        type: "POST",
        dataType: "json",
        success: function (data) {
            if (data.code == "000000") {
                $currentIntention = Number(!$currentIntention);
                $this.data('currentintention', $currentIntention);
                if ($currentIntention) {
                    $this.addClass('btn-success').html('<i class="mdi mdi-check-circle-outline"></i>取消意向');
                } else {
                    $this.removeClass('btn-success').html('<i class="mdi mdi-approval"></i>设为意向');
                }
                $('#contactList').bootstrapTable('refresh');
            } else {
                $.alert("操作失败");
            }
        }
    })
}

//移除计划
function updateFollowPlanTime(contactId) {
    $.ajax({
        url: "/contact/updateFollowPlanTime",
        async: true,
        data: {
            contactId: contactId
        },
        type: "POST",
        dataType: "json",
        success: function (data) {
            if (data.code == "000000") {
                $("#followPlanTimes").attr("style","display:none;");
            } else {
                $.alert("操作失败");
            }
            $('#contactList').bootstrapTable('refresh');
        }
    })
}

/**
 * 功能：添加标签相关功能
 * */
function tagsModal() {
    $('#tagsTable').bootstrapTable('destroy');
    $('#tagsTable').bootstrapTable({
        classes: 'table table-bordered table-hover table-striped',
        url: '/contact/contactTagList',                         // 请求地址
        method: 'post',                                         // 请求方式
        contentType: "application/x-www-form-urlencoded",       // 请求内容类型
        dataType: "json",                                       // 数据类型
        striped: true,                                          // 是否显示行间隔色
        sortable: true,                                         // 是否启用排序
        cache: false,                                           // 是否使用缓存
        showColumns: false,                                     // 显示隐藏列
        showRefresh: false,                                     // 显示刷新按钮
        showToggle: false,                                      // 切换显示样式
        showFooter: false,                                      // 显示Table脚部
        pagination: false,                                      // 是否显示分页
        clickToSelect: false,                                   // 是否启用点击选中行
        singleSelect: false,
        minimumCountColumns: 2,                                 // 最少要显示的列数
        undefinedText: '-',                                     // cell没有值时显示
        uniqueId: 'tagId',
        idField: 'tagId',
        queryParams: function (params) {                        // 查询参数
            params.pageSize = params.limit;
            params.pageIndex = (params.offset / params.limit) + 1;
            params.sortName = params.sort;
            params.sortOrder = params.order;
            return params;
        },
        columns: [
            {title: '标签ID', field: 'tagId', visible: false},
            {title: '标签名', field: 'tag', align: 'left', valign: 'middle'},
            {title: '操作', field: 'tag', align: 'right', valign: 'middle', width: '80',
                formatter: function (value, row, index) {
                    var html = '<button class="btn btn-default btn-danger" onclick="deleteTags(\'' + row.tagId + '\');"><i class="mdi mdi-delete"></i>删除</button>';
                    return html;
                }
            },
        ],
        responseHandler: function (result) {
            if (result.code == "000000") {
                var obj = {
                    "rows": result.data,
                    "total": result.totalRecords//总条数
                };
            } else {
                var obj = {
                    "total": 0,
                    "rows": [],
                }
            }
            return obj;
        },
        onLoadSuccess: function (data) {

        },
        onLoadError: function (status) {
            if (status == 403) {
                alert("权限不足！禁止访问！");
            } else {
                //加载失败时执行
                alert("加载失败！");
            }
        },
        formatLoadingMessage: function () {
            return "请稍等，加载中...";
        },
        formatNoMatches: function () {
            return '无符合条件的记录';
        },
    });
}
// 删除标签
function deleteTags(tagId) {
    $.ajax({
        url: '/contact/deleteContactTag',
        type: 'POST',
        dataType: "json",
        data: {
            tagId
        },
        success: function (data) {
            if (data.code == '000000') {
                $('#tagsTable').bootstrapTable('removeByUniqueId', tagId);
            } else {
                $.alert({
                    title: '系统提醒',
                    content: '删除标签出错，请稍后再试！（错误代码：' + data.code + '）'
                })
            }
        },
        error: function (err) {
            console.log(err);
        }
    })
}
// 添加标签
function addTags() {
    $.confirm({
        title: '新增标签',
        content: '<input type="text" placeholder="请输入标签内容，限5个字符" maxlength="5" class="tags-text form-control">',
        buttons: {
            cancel: {
                text: '取消',
                btnClass: 'btn-link'
            },
            formSubmit: {
                text: '提交',
                btnClass: 'btn-green',
                action: function () {
                    var tag = this.$content.find('.tags-text').val();
                    if(!tag){
                        $.alert({
                            title: '系统提醒',
                            content: '请输入标签内容！'
                        });
                        return false;
                    }
                    $.ajax({
                        url: '/contact/addContactTag',
                        type: 'POST',
                        dataType: "json",
                        data: {
                            tag
                        },
                        success: function (data) {
                            if (data.code == '000000') {
                                $('#tagsTable').bootstrapTable('refresh');
                            } else {
                                $.alert({
                                    title: '系统提醒',
                                    content: '删除标签出错，请稍后再试！（错误代码：' + data.code + '）'
                                })
                            }
                        },
                        error: function (err) {
                            console.log(err);
                        }
                    })
                }
            },
        },
        onContentReady: function () {
            var jc = this;
            this.$content.find('form').on('submit', function (e) {
                e.preventDefault();
                jc.$$formSubmit.trigger('click');
            });
        }
    });
}

/**
 * 功能：批处理
 * */
function batchFollow() {
    var followPlanTime = $('#batchDate').val();
    if (followPlanTime == '') {
        promptInfo('请选择跟进日期！');
        return;
    }
    var selectRowData = $('#contactList').bootstrapTable('getSelections');
    var contactIdArr = [];
    for (let i = 0; i < selectRowData.length; i++) {
        contactIdArr.push(selectRowData[i].contactId);
    }
    var data = {
        contactIds: contactIdArr,
        followPlanTime
    };
    $.ajax({
        url: '/contact/addContactFollowPlanTimes',
        type: 'POST',
        dataType: "json",
        contentType: "application/json;charset=utf-8",
        data: JSON.stringify(data),
        success: function (data) {
            if (data.code == '000000') {
                $('#batchDate').datepicker('clearDates');
                $('#batchCollapse').collapse('hide');
                // $('#contactList').bootstrapTable('refresh');
                $.alert({
                    title: '系统提示',
                    content: '批量设置计划跟进成功！',
                    buttons: {
                        confirm: {
                            text: '确认',
                            btnClass: 'btn-primary',
                            action: function () {
                                // $('#batchDate').datepicker('clearDates');
                                // $('#batchCollapse').collapse('hide');
                                $('#contactList').bootstrapTable('refresh');
                                $('#batchBtn').prop('disabled', true);
                            }
                        }
                    }
                });
            } else {
                promptInfo('处理失败，请稍后再试！(错误代码：' + data.code + ')');
            }
        },
        error: function (err) {
            promptInfo(err);
        }
    })
}
